<?php
/**
 * Created by PhpStorm.
 * User: alexey
 * Date: 8/2/14
 * Time: 11:02 AM
 */

namespace controller;

include_once("Mapping.php");

class Config
{

  private static $props;
  private static $files = array("cnf/config.properties");

  static function init()
  {
    if (self::$props == null) {
      for ($i = 0; $i < count(self::$files); $i++) {
        self::$props = self::parse(self::$files[$i]);
      }
    }
  }

  static function parse($smthToParse)
  {
    $splMap = new \SplObjectStorage();
    $f = file($smthToParse);
    $arrayLength = count($f);
    for ($i = 0; $i < $arrayLength; $i++) {
      $entry = self::getEntry($f[$i]);
      if ($entry) {
        $splMap->attach($entry);
      }
    }
    return $splMap;
  }

  private static function getEntry($parseString)
  {
    $keyEndPos = stripos($parseString, "=");
    if (!$keyEndPos) {
      return false;
    }
    $key = trim(substr($parseString, 0, $keyEndPos - 1));
    $content = trim(substr($parseString, $keyEndPos + 1, strlen($parseString)));

    $tmpEntry = new Entry();
    $tmpEntry->setKey($key);
    $tmpEntry->setContent($content);

    return $tmpEntry;
  }

  static function getPropertiesAsArray($keyPart)
  {
    $arr = null;
    self::init();

    self::$props->rewind();
    $count = self::$props->count();
    for ($i = 0; $i < $count; $i++) {
      if (strpos(self::$props->current()->getKey(), $keyPart) >= 0) {
        $arr[self::$props->current()->getKey()] = self::$props->current()->getContent();
      }
      self::$props->next();

    }

    return $arr;
  }

  static function getPropertyByKey($key) {
    self::init();

    self::$props->rewind();
    $count = self::$props->count();
    for ($i = 0; $i < $count; $i++) {
      if (self::$props->current()->getKey() == trim($key)) {
        return self::$props->current()->getContent();
      }
      self::$props->next();
    }

    return false;
  }

}